﻿using System.Collections.Generic;
using System.Linq;
using Kratos.Framework.ContentManagement.Models.SystemRights;
using Kratos.Framework.Extensions;
using Kratos.Framework.Function;
using Kratos.Framework.Infrastructures;
using Kratos.Framework.Modules.Core.Repositories;
using Kratos.Framework.Repositories;

namespace Kratos.Framework.Modules.Core.Services.Impl
{
    public class ActionPermissionService : IActionPermissionService
    {
        private readonly IRepository<ActionPermission> _actionPermissionRepository;

        public ActionPermissionService(IRepository<ActionPermission> apRep)
        {
            _actionPermissionRepository = apRep;
        }

        public IEnumerable<ActionPermission> GetAllSystemActions()
        {
            return SecurityHelper.Actions;
        }

        public bool IsExistActionPermission(ActionPermission model)
        {
            return _actionPermissionRepository.GetAll().IsExistActionPermission(model);
        }

        public void Save(ActionPermission model)
        {
            _actionPermissionRepository.Save(model);
        }

        public void Delete(ActionPermission model)
        {
            _actionPermissionRepository.DeleteOnSubmit(model);
        }

        public PageList<ActionPermission> GetByPage(int pageIndex, int pageSize)
        {
            return GetAll().ToPageList(pageIndex, pageSize);
        }

        public IEnumerable<ActionPermission> GetAll()
        {
            if (KratosCache.Get<IEnumerable<ActionPermission>>("System_ActionPermissions") == null)
            {
                var all = _actionPermissionRepository.GetAll().ToList();
                KratosCache.Set("System_ActionPermissions", all);
            }
            return KratosCache.Get<IEnumerable<ActionPermission>>("System_ActionPermissions");
        }

        public void ResetCache()
        {
            var all = _actionPermissionRepository.GetAll().ToList();
            KratosCache.Set("System_ActionPermissions", all);
        }
    }
}
